<template>
  <div class="salary-records">
    <div class="page-header">
      <div class="page-title">薪资记录</div>
      <template v-if="!isEmployee">
        <el-button type="primary" @click="openBatchDialog" style="margin-left:8px;">批量生成本月薪资</el-button>
        <el-button type="danger" @click="openDeleteDialog" style="margin-left:8px;">一键删除本月薪资</el-button>
        <el-button type="success" @click="handleExport" style="margin-left:8px;">导出Excel</el-button>
        <el-button type="warning" @click="openPayDialog" style="margin-left:8px;">批量发放工资</el-button>
      </template>
    </div>
    <el-dialog v-model="batchDialogVisible" title="批量生成薪资记录" width="400px">
      <el-form :model="batchForm" label-width="80px">
        <el-form-item label="年份">
          <el-input-number v-model="batchForm.year" :min="2000" :max="2100" />
        </el-form-item>
        <el-form-item label="月份">
          <el-input-number v-model="batchForm.month" :min="1" :max="12" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="handleBatchGenerate" :loading="batchLoading">生成</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="deleteDialogVisible" title="一键删除本月薪资记录" width="400px">
      <el-form :model="deleteForm" label-width="80px">
        <el-form-item label="年份">
          <el-input-number v-model="deleteForm.year" :min="2000" :max="2100" />
        </el-form-item>
        <el-form-item label="月份">
          <el-input-number v-model="deleteForm.month" :min="1" :max="12" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="deleteDialogVisible=false">取消</el-button>
        <el-button type="danger" @click="handleBatchDelete" :loading="deleteLoading">删除</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="payDialogVisible" title="批量发放工资" width="400px">
      <el-form :model="payForm" label-width="80px">
        <el-form-item label="年份">
          <el-input-number v-model="payForm.year" :min="2000" :max="2100" />
        </el-form-item>
        <el-form-item label="月份">
          <el-input-number v-model="payForm.month" :min="1" :max="12" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="payDialogVisible=false">取消</el-button>
        <el-button type="warning" @click="handleBatchPay" :loading="payLoading">发放</el-button>
      </template>
    </el-dialog>
    <div class="table-container">
      <el-table :data="records" border style="width: 100%" v-loading="loading">
        <el-table-column prop="userName" label="姓名" width="100" />
        <el-table-column prop="userDepartment" label="部门" width="120" />
        <el-table-column prop="userPosition" label="岗位" width="120" />
        <el-table-column prop="year" label="年份" width="80" />
        <el-table-column prop="month" label="月份" width="80" />
        <el-table-column prop="schemeName" label="薪资方案" width="150" />
        <el-table-column prop="baseSalary" label="基本工资" width="100">
          <template #default="{ row }">¥{{ formatMoney(row.baseSalary) }}</template>
        </el-table-column>
        <el-table-column prop="attendanceDeduction" label="考勤扣款" width="100">
          <template #default="{ row }">-¥{{ formatMoney(row.attendanceDeduction) }}</template>
        </el-table-column>
        <el-table-column prop="socialSecurity" label="社保" width="100">
          <template #default="{ row }">-¥{{ formatMoney(row.socialSecurity) }}</template>
        </el-table-column>
        <el-table-column prop="housingFund" label="公积金" width="100">
          <template #default="{ row }">-¥{{ formatMoney(row.housingFund) }}</template>
        </el-table-column>
        <el-table-column prop="tax" label="个税" width="100">
          <template #default="{ row }">-¥{{ formatMoney(row.tax) }}</template>
        </el-table-column>
        <el-table-column prop="totalSalary" label="税前工资" width="120">
          <template #default="{ row }">¥{{ formatMoney(row.totalSalary) }}</template>
        </el-table-column>
        <el-table-column prop="netSalary" label="实发工资" width="120">
          <template #default="{ row }">
            <el-tag type="success">¥{{ formatMoney(row.netSalary) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="120" />
        <el-table-column v-if="isEmployee" prop="action" label="操作" width="100">
          <template #default="{ row }">
            <el-button v-if="row.status === 'PENDING'" type="primary" size="small" @click="handleConfirm(row)">确认</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin: 20px 0; text-align: right;"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="pageNum"
        @current-change="handlePageChange"
        @size-change="handleSizeChange"
        :page-sizes="[5, 10, 20, 50, 100]"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const loading = ref(false)
const records = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)

// 批量生成相关
const batchDialogVisible = ref(false)
const batchLoading = ref(false)
const now = new Date()
const batchForm = ref({
  year: now.getFullYear(),
  month: now.getMonth() + 1
})
const openBatchDialog = () => {
  batchDialogVisible.value = true
}
const handleBatchGenerate = async () => {
  batchLoading.value = true
  try {
    await axios.post('/salary/batch-generate', null, {
      params: {
        year: batchForm.value.year,
        month: batchForm.value.month
      }
    })
    ElMessage.success('批量生成成功！')
    batchDialogVisible.value = false
    fetchRecords()
  } catch (e) {
    ElMessage.error('批量生成失败')
  } finally {
    batchLoading.value = false
  }
}

// 一键删除相关
const deleteDialogVisible = ref(false)
const deleteLoading = ref(false)
const deleteForm = ref({
  year: now.getFullYear(),
  month: now.getMonth() + 1
})
const openDeleteDialog = () => {
  deleteDialogVisible.value = true
}
const handleBatchDelete = async () => {
  deleteLoading.value = true
  try {
    await axios.delete('/salary/batch-delete', {
      params: {
        year: deleteForm.value.year,
        month: deleteForm.value.month
      }
    })
    ElMessage.success('删除成功！')
    deleteDialogVisible.value = false
    fetchRecords()
  } catch (e) {
    ElMessage.error('删除失败')
  } finally {
    deleteLoading.value = false
  }
}

const isEmployee = ref(false)

const fetchRecords = async () => {
  try {
    loading.value = true
    const response = await axios.get('/salary/records', {
      params: {
        pageNum: pageNum.value,
        pageSize: pageSize.value
      }
    })
    const data = response.data || {}
    records.value = Array.isArray(data.records) ? data.records : []
    total.value = typeof data.total === 'number' ? data.total : 0
    loading.value = false
  } catch (error) {
    ElMessage.error('获取薪资记录失败')
    loading.value = false
  }
}

const handlePageChange = (newPage) => {
  pageNum.value = newPage
  fetchRecords()
}
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  pageNum.value = 1
  fetchRecords()
}

const formatMoney = (amount) => {
  if (!amount) return '0.00'
  return Number(amount).toFixed(2)
}

const getStatusTagType = (status) => {
  if (status === 'PAID') return 'success'
  if (status === 'CONFIRMED') return 'warning'
  return 'info'
}
const getStatusText = (status) => {
  if (status === 'PAID') return '已发放'
  if (status === 'CONFIRMED') return '已确认'
  return '待确认'
}

const handleExport = async () => {
  const params = [];
  if (batchForm.value.year) params.push(`year=${batchForm.value.year}`);
  if (batchForm.value.month) params.push(`month=${batchForm.value.month}`);
  const url = '/salary/export' + (params.length ? '?' + params.join('&') : '');
  try {
    const res = await axios.get(url, { responseType: 'blob' });
    const blob = new Blob([res.data], { type: res.headers['content-type'] });
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = '薪资记录.xlsx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(link.href);
  } catch (e) {
    ElMessage.error('导出失败');
  }
}

const handleConfirm = async (row) => {
  try {
    await axios.post(`/salary/confirm/${row.id}`)
    ElMessage.success('确认成功')
    fetchRecords()
  } catch (e) {
    ElMessage.error('确认失败')
  }
}

const payDialogVisible = ref(false)
const payLoading = ref(false)
const payForm = ref({
  year: now.getFullYear(),
  month: now.getMonth() + 1
})
const openPayDialog = () => {
  payDialogVisible.value = true
}
const handleBatchPay = async () => {
  payLoading.value = true
  try {
    await axios.post('/salary/batch-pay', null, {
      params: {
        year: payForm.value.year,
        month: payForm.value.month
      }
    })
    ElMessage.success('批量发放成功！')
    payDialogVisible.value = false
    fetchRecords()
  } catch (e) {
    ElMessage.error('批量发放失败')
  } finally {
    payLoading.value = false
  }
}

onMounted(async () => {
  // 判断当前用户角色（假设后端返回有userRole字段，或可通过接口获取）
  try {
    const res = await axios.get('/user/info')
    isEmployee.value = res.data && res.data.role === 'EMPLOYEE'
  } catch {}
  fetchRecords()
})
</script>

<style scoped>
.salary-records {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.page-title {
  font-size: 18px;
  font-weight: bold;
}
.table-container {
  margin-top: 20px;
}
</style> 